let app = getApp()
let cs = app.data.common_store
import mqtt from '../common/lib/mqtt.js';

let connect = () => {
	return new Promise((done_fn, fail_fn) => {
		if(!cs.mqtt.connected && !cs.mqtt.connecting) {
			cs.mqtt.connecting = true
			// 生成随机ID
			create_client_id()
			cs.mqtt.conn = mqtt.connect(cs.mqtt.host, cs.mqtt.options);
			// console.log(cs.mqtt.conn)
			// 连接成功后订阅
			cs.mqtt.conn.on("connect", () => {
				app.set_state("mqtt", true)
				cs.mqtt.conn.subscribe(cs.mqtt.topic, ({
					qos: cs.mqtt.qos,
				}))
				// 将正在连接标识置否
				cs.mqtt.connecting = false
				cs.mqtt.connected = true
				done_fn()
			})
		}
		else {
			fail_fn()
		}
	})
}

let create_client_id = () => {
	// cs.mqtt.options.clientId = Math.random().toString(36).slice(2, 12)
	// console.log(cs.mqtt.options.clientId)
	let chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	let result = '';
	for (var i = cs.mqtt.client_id_length; i > 0; --i) {
		result += chars[Math.floor(Math.random() * chars.length)]
	}
	cs.mqtt.options.clientId = result
	// console.log("client id: ", cs.mqtt.options.clientId)
}

let send = (msg) => {
	if (cs.mqtt.connected && msg != "") {
		msg = cs.mqtt.options.clientId + cs.mqtt.split_code + cs.settings.callsign + cs.mqtt.split_code + msg
		// console.log(" mqtt send : " + msg)
		cs.mqtt.conn.publish(cs.mqtt.topic, msg)
	}
	else {
		console.log("mqtt connected false")
	}
}

let send_code = () => {
	if(cs.input_code.code != ""){
		send(cs.input_code.code)
		cs.input_code.show = ""
		cs.input_code.code = ""
		cs.input_code.temp = ""
	}
}
let clear_code = () => {
	cs.input_code.show = ""
	cs.input_code.code = ""
	cs.input_code.temp = ""
}

let end = () => {
	console.log("mqtt end")
	cs.mqtt.conn.end("force")
	cs.mqtt.connected = false
	app.set_state("mqtt", false)
}

let del_last = () => {
	if(cs.input_code.code.length > 0) {
		let sp_num = -1
		let code_list = cs.input_code.code.split(" ")
		let show_list = cs.input_code.show.split(" ")
		if(code_list[code_list.length - 1] == " " || code_list[code_list.length - 1] == "") {
			sp_num = -2
		}
		cs.input_code.code = code_list.slice(0, sp_num).join(" ")
		cs.input_code.show = show_list.slice(0, sp_num).join(" ")

	}
}

module.exports = {
	connect: connect,
	send: send,
	end: end,
	send_code: send_code,
	clear_code: clear_code,
	del_last: del_last,
}